package com.fingard.dsp.bank.directbank.psbc01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.helpers.DataFileHelper;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.util.PdfGenerateUtil;
import com.fingard.util.SmbFileUtil;
import com.fingard.util.ZipHelper;

import java.io.File;
import java.util.Calendar;
import java.util.Date;

import static com.fingard.text.StringHelper.trimEndFileSp;

/**
 * @author Parker on 2019-09-03.
 * @version 1.0
 */
public class PSBC01Receipt extends PSBC01Base implements IReceipt {
    @Override
    public RetAtsReceipt qryReceipt(ReqQryReceipt p_reqReceipt) throws Exception {
        //电子回单查询返回ATS的对象
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        String receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
        if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
            if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                    download(p_reqReceipt, retAts);
                } else {
                    retAts.respInfo = "DSPSystem未配置回单文件推送地址";
                    retAts.respCode = "-1";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "DSPSystem未配置回单文件共享目录";
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "DSPSystem未配置回单文件下载保存主目录";
        }
        retAts.writeRetToATS();
        return retAts;
    }

    private void download(ReqQryReceipt p_reqReceipt, RetAtsReceipt retAts) {
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());
            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            StringBuilder json = new StringBuilder();
            json.append("transType=downloadreceipt&data={\"rows\":[");
            DataFileHelper dFileHelper = new DataFileHelper(this);
            StringBuilder tempMSG = new StringBuilder();
            int tmpFileCount = 0;
            while (tmpIntFrom <= tmpIntTo) {
                /**
                 * 银行每天结束会把当日回单推送到指定FTP服务器, pdf文件名是:日期+流水号规则.pdf，压缩文件名是:账号+日期规则.zip
                 */
                String fileName = p_reqReceipt.actNum+"_"+ tmpIntFrom + "_3.zip";
                String receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
                String localRecepitPath = receiptSaveToMainDir + File.separator + p_reqReceipt.reqHeader.bankCode + File.separator + tmpIntFrom;
                FtpSet ftpSet = bankFront.getFtpSet("receipt");
                String downFilePath = trimEndFileSp(ftpSet.downDir);
                WriteBankLogLn("FTP下载地址" + ftpSet.serverIP + ":" + ftpSet.port);
                WriteBankLogLn("开始下载服务器文件" + downFilePath + "至本地文件" + receiptSaveToMainDir);
                FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
                ftpPtClient.connect();
                FtpReceiver tmpReceiver = ftpPtClient.downloadFile(downFilePath + File.separator + fileName, localRecepitPath + File.separator + fileName);
                if (tmpReceiver.connState.length() == 0 && tmpReceiver.isCompleted) {
                    WriteBankLogLn("文件下载已完成，开始解压...");
                    WriteBankLogLn("解压至：[" + localRecepitPath + "]");
                    ZipHelper.unZipFiles(localRecepitPath + File.separator + fileName, localRecepitPath);
                    WriteBankLogLn("文件解压已完成.");
                    File depressDir = new File(localRecepitPath + File.separator + fileName.replace(".zip", ""));
                    String destPath = depressDir.getAbsolutePath();
                    String[] files = FileHelper.listFiles(destPath);
                    if (files == null || files.length == 0) {
                        WriteBankLogLn("解压后文件夹" + destPath + "下为空");
                    } else {
                        for (String file : files) {
                            String localRecipt = destPath + File.separator + file;
                            if ((file.endsWith(".PDF") || file.endsWith(".pdf"))) {
                                int result = -1;
                                WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                String tmpByDate = Format.Date8Format.format(new Date());
                                tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/"
                                        + reqHeader.bankCode + "/" + p_reqReceipt.actNum + "/";
                                if (new File(localRecipt).exists()) {
                                    WriteBankLogLn(
                                            "正在上传文件至共享目录1:" + FGBiz.dspCenter.dspSet.receiptShareDir + tmpByDate);
                                    result = SmbFileUtil.smbUploading(localRecipt, tmpByDate,
                                            FGBiz.dspCenter.dspSet.receiptShareDir);
                                }
                                if (result == 0 || result == 1) {
                                    if (result == 0) {
                                        WriteBankLogLn("文件上传成功");
                                        tmpFileCount++;
                                    } else {
                                        WriteBankLogLn("文件已存在共享目录无需重复上传");
                                    }
                                    //解析PDF获取回单数据
                                    String[] pdfText = PdfGenerateUtil.readPDFTable(localRecipt, 1000, 800).split("\r\n");
                                    String receiptCode = pdfText[1].substring(pdfText[1].indexOf("电子回单号码：")+7,pdfText[1].indexOf(" (第"));
                                    json.append("{");
                                    json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");
                                    json.append("\"actCur\":\"" + p_reqReceipt.actCur + "\",");
                                    json.append("\"receiptCode\":\"" + receiptCode + "\",");
                                    json.append("\"receiptType\":\"" + "" + "\",");
                                    json.append("\"receiptState\":\"" + "" + "\",");
                                    //付款账户
                                    String payAct = pdfText[5].split("款 账 号 ")[1].trim();
                                    String payActName = pdfText[3].split("户 名 ")[1].trim();
                                    //收款账户
                                    String recAct = pdfText[5].split("款 账 号 ")[2].trim();
                                    String recActName = pdfText[3].split("户 名 ")[2].trim();

                                    if (p_reqReceipt.actNum.equals(recAct)) {
                                        json.append("\"oppActName\":\"" + payActName + "\",");
                                        json.append("\"oppActNum\":\"" + payAct + "\",");
                                        json.append("\"moneyway\":\"" + "2" + "\",");
                                    } else {
                                        json.append("\"oppActName\":\"" + recActName + "\",");
                                        json.append("\"oppActNum\":\"" + recAct + "\",");
                                        json.append("\"moneyway\":\"" + "1" + "\",");
                                    }
                                    json.append("\"amount\":\"" + pdfText[9].substring(pdfText[9].indexOf("小写：")+3,pdfText[9].indexOf("大写")).trim() + "\",");
                                    json.append("\"tranSeqNo\":\"" + pdfText[12].substring(pdfText[12].indexOf("交易流水号 ")+6) + "\",");
                                    json.append("\"tranCode\":\"" + "" + "\",");
                                    json.append("\"tranDate\":\"" + Format.Date10Format.format(tmpCalendarFrom.getTime()) + "\",");
                                    json.append("\"filePath\":\"" + tmpByDate
                                            + StringHelper.getFileName(localRecipt) + "\",");
                                    json.append("\"fileType\":\"1\"");
                                    json.append("},");
                                } else {
                                    WriteBankLogLn(tmpIntFrom + ":上传文件至共享目录失败，请检查共享目录配置是否正确 ");
                                    break;
                                }
                            } else {
                                WriteBankLogLn("PDF名称不正确:" + localRecipt);
                            }
                        }
                    }
                } else {
                    WriteBankLogLn(tmpReceiver.connMsg);
                }
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            }
            WriteBankLogLn("成功保存了" + tmpFileCount + "个文件");
            retAts.respCode = "0";
            retAts.respInfo = "成功保存了" + tmpFileCount + "个文件" + tempMSG;
            WriteBankLogLn("成功保存了" + tmpFileCount + "个文件" + tempMSG);
            json.append("]}");
            if (tmpFileCount > 0) {
                String[] data = sendToATS(json.toString());
                if (data[0].length() == 0 && "ok".equals(data[1])) {
                    retAts.respCode = "0";
                    retAts.respInfo = "推送数据到ATS成功,请查看数据";
                    WriteBankLogLn("推送数据到ATS成功,请查看数据");
                } else {
                    retAts.respCode = "0";
                    retAts.respInfo = "推送数据到ATS失败";
                    WriteBankLogLn("推送数据到ATS失败");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
    }
}
